package eu.ioc.factory;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import stub.ioc.Student;

/**
 * 类厂
 * @author wzz
 *
 */
public class BeansFactory {
	Document xml = null;
	
	public BeansFactory(String path){
		SAXReader sr = new SAXReader();
		try {
			xml = sr.read(new File(path));
		} catch (DocumentException e) {
			e.printStackTrace();
			return;
		}
	}
	
	public Object getBean(String id) throws Exception{
		Element beanEle = BeanMaker.locateBean(xml, id);
		String clazz = beanEle.attributeValue("class");
		Object instance = BeanMaker.createBean(clazz);
		for (Object beanEles : beanEle.selectNodes("property")) {
			Element proEle = (Element) beanEles;
			BeanMaker.setProperty(Class.forName(clazz), instance, proEle);
		}
		return instance;
	}
	
	public static void main(String[] args) throws Exception {
		BeansFactory fac = new BeansFactory(
				BeansFactory.class.getResource("/").getPath()+"beans.xml");
		Student stu = (Student) fac.getBean("default.student");
		System.out.println(stu.getStudent().getName());
		for (String s : stu.getObj())
			System.out.println(s);
		System.out.println(stu.getTime());
	}
}
